/**
 * 向后端请求用户的菜单，动态生成路由
 */
import { constantRouterMap } from '@/config/router.config'
import { generatorDynamicRouter } from '@/router/generator-routers'

/* 删减路由 */
const cutRouter = (isadmin, scope, routers) => {
  routers.forEach((item, index) => {
    if (!isadmin) { // 普通员工
      if (item.access && (item.access === 'admin' || item.access === 'manager')) {
        delete routers[index]
      }
    } else if (isadmin && scope !== 1) { // 普通管理员
      if (item.access && item.access === 'admin') {
        delete routers[index]
      }
    }
    if (item.children) {
      cutRouter(isadmin, scope, item.children);
    }
  })
  return routers;
}

// 清除空菜单
const removeEmptyRouter = (routers) => {
  if (routers) {
    routers.map((item, index) => {
      if (item.children) {
        if (item.children.length === 0) {
          delete routers[index];
        } else {
          if (item.children[0] === undefined) {
            delete routers[index];
          }
          removeEmptyRouter(item.children);
        }
      }
    })
  }
  return routers;
}

const permission = {
  state: {
    routers: constantRouterMap,
    addRouters: []
  },
  mutations: {
    SET_ROUTERS: (state, routers) => {
      state.addRouters = routers
      state.routers = constantRouterMap.concat(routers)
    },
    CLEAN_ROUTERS: (state) =>{
      state.addRouters = []
      state.routers = constantRouterMap
    }
  },
  actions: {
    GenerateRoutes ({ commit }, data) {
      return new Promise(resolve => {
        const { token } = data
        generatorDynamicRouter(token).then(routers => {
          // let currentUser = storage.get(APP_USER);
          // // 删减菜单
          // let rtx = cutRouter(currentUser.isadmin, currentUser.scope, routers);
          // // 去除空菜单
          // rtx = removeEmptyRouter(rtx);
          commit('SET_ROUTERS', routers)
          resolve()
        })
      })
    },
    cleanRouters ({ commit }) {
      return new Promise(resolve => {
        commit('CLEAN_ROUTERS')
        resolve()
      })
    }
  }
}

export default permission
